package com.kajespero.webapp.controller.commons;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kajespero.model.ArticleBean;
import com.kajespero.model.PageBean;
import com.kajespero.model.SummaryBean;
import com.kajespero.model.TemplateBean;
import com.kajespero.model.UserBean;
import com.kajespero.service.article.ArticleService;
import com.kajespero.service.article.impl.ArticleServiceImpl;
import com.kajespero.service.page.PageService;
import com.kajespero.service.page.impl.PageServiceImpl;
import com.kajespero.service.site.SiteService;
import com.kajespero.service.site.impl.SiteServiceImpl;
import com.kajespero.service.summary.SummaryService;
import com.kajespero.service.summary.impl.SummaryServiceImpl;
import com.kajespero.service.template.TemplateService;
import com.kajespero.service.template.impl.TemplateServiceImpl;
import com.kajespero.service.user.UserService;
import com.kajespero.service.user.impl.UserServiceImpl;
import com.kajespero.vo.UserVO;
import com.kajespero.webapp.AttributesConstants;

@Controller
@RequestMapping(value = "/")
public class RootController {

	private static final TemplateService TEMPLATE_SERVICE = new TemplateServiceImpl();

	private static final SiteService SITE_SERVICE = new SiteServiceImpl();

	private static final SummaryService SUMMARY_SERVICE = new SummaryServiceImpl();

	private static final ArticleService ARTICLE_SERVICE = new ArticleServiceImpl();

	private static final PageService PAGE_SERVICE = new PageServiceImpl();
	
	private static final UserService USER_SERVICE = new UserServiceImpl();
	
	private static final Log LOG = LogFactory.getLog(RootController.class);

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public void get(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setContentType("text/html; charset=UTF-8");	
		Collection<UserBean> users = (Collection<UserBean>) request.getSession()
				.getServletContext()
				.getAttribute(AttributesConstants.USERS_ATTRIBUTES);
		if(users == null){
			LOG.debug("test ok je passe ici ");
			users = USER_SERVICE.findAll();
			request.getSession()
			.getServletContext()
			.setAttribute(AttributesConstants.USERS_ATTRIBUTES, users);
		}
		if (users.isEmpty()) {
			String req = response.encodeRedirectURL("/user/create_user");
			response.sendRedirect(req);
		}
		String path = (String) request.getParameter(AttributesConstants.PATH);
		UserVO administrator = (UserVO) request.getSession().getAttribute(
				AttributesConstants.ADMINISTRATOR);
		Collection<SummaryBean> summaries = SUMMARY_SERVICE.findAll();

		if (StringUtils.equalsIgnoreCase("/create_administration", path)
				&& summaries.isEmpty()) {
			SITE_SERVICE.initSite(administrator);
			String req = response.encodeRedirectURL("/index?path=/");
			response.sendRedirect(req);
		} else {
			if (StringUtils.isNotEmpty(path)) {
				Collection<PageBean> pages = SUMMARY_SERVICE
						.findPageBySummary(path);
				if (pages != null) {
					for (PageBean page : pages) {
						SummaryBean summaryBean = page.getSummary();
						if (summaryBean != null
								&& StringUtils.isNotBlank(summaryBean.getUrl())) {
							if (StringUtils.equalsIgnoreCase("/administration",
									summaryBean.getUrl())) {
								if (administrator == null) {
									String req = response
											.encodeRedirectURL("/user/login");
									response.sendRedirect(req);
								} else {
									TemplateBean template = (TemplateBean) page.getTemplate();
									if(template == null){
										template = TEMPLATE_SERVICE.findByName("Administration-Template");
										page.setTemplate(template);
									}
									response.setContentType("text/html; charset=UTF-8");
									response.getWriter().println(
											TEMPLATE_SERVICE.parseTemplate(
													page.getTemplate(),
													createAdministrationMap(
															users,
															administrator)));
								}
							} else {
								List<ArticleBean> articles = (List<ArticleBean>) ARTICLE_SERVICE
										.findByPage(page);
								response.setContentType("text/html; charset=UTF-8");
								TemplateBean templatePage = TEMPLATE_SERVICE
										.findByName("Page-Template");
								Map<String, Object> mapValues = new HashMap<String, Object>();
								mapValues.put("articles", articles);
								mapValues.put("page", page);
								mapValues.put("summariesMap",
										SUMMARY_SERVICE.summariesMap());
								response.getWriter().println(
										TEMPLATE_SERVICE.parseTemplate(
												templatePage, mapValues));
							}
						}
						else{
							response.setContentType("text/html; charset=UTF-8");
							response.getWriter().println("<html><body><p>Sorry there is a probreme with this page please contact the administrator summary null or url blanck<p></body></html>");
						}
					}
				}
				else {
					response.setContentType("text/html; charset=UTF-8");
					response.getWriter().println("<html><body><p>Sorry there is a probreme with this page please contact the administrator "+path +"<p></body></html>");
				}

			} else {
				String req = response.encodeRedirectURL("/");
				response.sendRedirect(req);
			}
		}
	}

	@RequestMapping(value = "/")
	public void index(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String req = response.encodeRedirectURL("/index?path=/");
		response.sendRedirect(req);
	}

	private Map<String, Object> createAdministrationMap(
			Collection<UserBean> users, UserVO administrator) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("users", users);
		map.put("administrator", administrator);
		Collection<TemplateBean> templates = TEMPLATE_SERVICE.findAll();
		map.put("templates", templates);
		Collection<ArticleBean> articles = ARTICLE_SERVICE.findAll();
		map.put("articles", articles);
		Collection<PageBean> pages = PAGE_SERVICE.findAll();
		map.put("pages", pages);
		Collection<SummaryBean> summaries = SUMMARY_SERVICE.findAll();
		map.put("summaries", summaries);
		map.put("summariesMap", SUMMARY_SERVICE.summariesMap());
		return map;
	}
}
